<?php
/**
 * @copyright
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\admin\controller;

use app\common\service\ElasticsearchService;
use app\admin\BaseController;
use app\admin\model\News as NewsModel;
use app\admin\validate\NewsValidate;
use app\api\controller\Alicloud;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class News extends BaseController

{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new NewsModel();
        $this->uid   = get_login_admin('id');
    }

    /**
     * 数据列表
     */
    public function datalist()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $where   = [];
            $where[] = ["delete_time", "=", 0];
            $where[] = ["news_file_id", "=", 0];
            if (!empty($param['uid'])) {
                //查看公海信息
                $hai     = Db::name('hai')->where(['uid' => $param['uid'], 'type' => 1, 'delete_time' => 0])->column('news_id');
                $where[] = ['id', 'in', $hai];
            }

            $conditions = [
                'delete_time'  => 0,
                'news_file_id' => 0
            ];

            // 记录性能
            $timing      = [];
            $start_total = microtime(true);

            if (!empty($param['province_id'])) {
                $province               = Db::name('citys')->where('id', $param['province_id'])->value('name');
                $conditions['province'] = $province;
            }
            if (!empty($param['city_id'])) {
                $city               = Db::name('citys')->where('id', $param['city_id'])->value('name');
                $conditions['city'] = $city;
            }
            if (!empty($param['district_id'])) {
                $district               = Db::name('citys')->where('id', $param['district_id'])->value('name');
                $conditions['district'] = $district;
            }
            if (!empty($param['cate_one'])) {
                $conditions['cate_one'] = $param['cate_one'];
            }
            if (!empty($param['cate_two'])) {
                $conditions['cate_two'] = $param['cate_two'];
            }
            if (!empty($param['yingye_id'])) {
                $ying = [];
                foreach ($param['yingye_id'] as $item) {
                    $parts = explode('/', $item); // 每个值可能像 "迁入/迁出"
                    $ying  = array_merge($ying, $parts); // 合并进 $ying 数组
                }
                $conditions['status_in'] = $ying;
            }
            if (!empty($param['lianxi'])) {
                $conditions['lianxi'] = $param['lianxi'];
            }
            if (!empty($param['riqi_year'])) {
                $conditions['riqi_year'] = implode(',', $param['riqi_year']);
            }
            if (!empty($param['zhuce'])) {
                $conditions['zhuce'] = implode(',', $param['zhuce']);
            }
            if (!empty($param['leixing'])) {
                $conditions['leixing'] = $param['leixing'];
            }
            if (!empty($param['canbao'])) {
                $conditions['canbao'] = $param['canbao'];
            }

            // 处理其他条件
            foreach (['zhaopin', 'wangluo', 'yuming', 'shangbiao', 'zhuanli', 'zhaobiao', 'gongzhong'] as $field) {
                if (!empty($param[$field])) {
                    $conditions[$field] = $param[$field];
                }
            }

            if (!empty($param['keys'])) {
                $conditions['keys'] = $param['keys'];
            }
            $isBasicQuery = (count($conditions) == 2);
            if (!$isBasicQuery) {
                // 使用Elasticsearch服务查询
                $start_es  = microtime(true);
                $esService = new ElasticsearchService();
                $page      = !empty($param['page']) ? (int)$param['page'] : 1;
                $pageSize  = !empty($param['limit']) ? (int)$param['limit'] : 20;;
                $isBasicQuery = (count($conditions) == 2);

                $result = $esService->searchNews($conditions, $page, $pageSize);

                $total = $result['total'];


                $list = $result['list'];


                $return = [
                    'per_page'     => $pageSize,
                    'current_page' => $page,
                    //  'ids' => $ids,
                    'total'        => $total,
                    'data'         => $list,
                    '_debug'       => $timing // 仅在调试模式下显示

                ];


            } else {
                $return = $this->model->getNewsList($where, null, null);
                // var_dump($return);
            }
            return table_assign(0, '', $return);
        } else {
            $cate     = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0])->order('sort asc')->select();
            $cityList = Db::name('citys')->where(['level' => 1])->order('id asc')->select();
            $svipCate = Db::name('news_file')->where(['delete_time' => 0])->order('sort asc')->select();
            $uid      = 0;
            if (!empty($param['uid'])) {
                $uid = $param['uid'];
            }
            $qiCate = Db::name('qi_cate')->where(['delete_time' => 0])->order('id desc')->select();
            View::assign('qiCate', $qiCate);
            View::assign('uid', $uid);
            View::assign('svipCate', $svipCate);
            View::assign('cityList', $cityList);
            View::assign('cate', $cate);
            return view();
        }
    }
//   public function datalist()
//     {
//         $param = get_params();
//         if (request()->isAjax()) {
// 			$where = [];
// // 			$where[] = ["delete_time","=",0];
// //             $where[] = ["news_file_id","=",0];
//             if (!empty($param['uid'])) {
//                 //查看公海信息
//                 $hai = Db::name('hai')->where(['uid'=>$param['uid'],'type'=>1,'delete_time'=>0])->column('news_id');
//                 $where[] = ['id','in',$hai];
//             }
//             if (!empty($param['news_file_id'])) {
//                 $where[] = ['news_file_id','=',$param['news_file_id']];
//             }
//             if (!empty($param['province_id'])) {
//                 $province = Db::name('citys')->where('id',$param['province_id'])->value('name');
//                 $where[] = ['province',"=","{$province}"];
//             }
//             if (!empty($param['city_id'])) {
//                 $city = Db::name('citys')->where('id',$param['city_id'])->value('name');
//                 $where[] = ['city','=',"{$city}"];
//             }
//             if (!empty($param['district_id'])) {
//                 $district = Db::name('citys')->where('id',$param['district_id'])->value('name');
//                 $where[] = ['district','=',"{$district}"];
//             }
//             if (!empty($param['cate_one'])) {
//                 $where[] = ['cate_one','=',$param['cate_one']];
//             }
//             if (!empty($param['cate_two'])) {
//                 $where[] = ['cate_two','=',$param['cate_two']];
//             }
//             if (!empty($param['yingye_id'])) {
//                 $yingye_id = implode('/',$param['yingye_id']);
//                 $ying = explode('/',$yingye_id);
//                 $ying_arr = array_merge($param['yingye_id'],$ying);
//                 $where[] = ['status','in',$ying_arr];
//             }
//             if (!empty($param['lianxi'])) {
//                 foreach ($param['lianxi'] as &$v1) {
//                     if ($v1 == '有电话') {
//                         $where[] = ['has_mobile','=','1'];
//                     } elseif ($v1 == '有固话') {
//                         $where[] = ['mobile_more','<>',''];
//                     } elseif ($v1 == '有邮箱') {
//                         $where[] = ['emails','<>',''];
//                     } elseif ($v1 == '有QQ') {
//                         $where[] = ['qq','<>',''];
//                     } elseif ($v1 == '无联系方式') {
//                         $where[] = ['has_mobile','=','0'];
//                         $where[] = ['mobile_more','=',''];
//                     }
//                 }
//             }
//             $riqi_sql = '';
//             if (!empty($param['riqi_year'])) {
//                 foreach ($param['riqi_year'] as &$v2) {
//                     if ($v2 == '1年以内') {
//                         if (empty($riqi_sql)) {
//                             $riqi_sql .= 'riqi_year < 1 ';
//                         } else {
//                             $riqi_sql .= 'OR riqi_year < 1 ';
//                         }
//                         continue;
//                     }
//                     if ($v2 == '15年以上') {
//                         if (empty($riqi_sql)) {
//                             $riqi_sql .= 'riqi_year >= 15 ';
//                         } else {
//                             $riqi_sql .= 'OR riqi_year >= 15 ';
//                         }
//                         continue;
//                     }
//                     $years = explode('-',$v2);
//                     if (empty($riqi_sql)) {
//                         $riqi_sql .= 'riqi_year between '.$years[0].' AND '.$years[1].' ';
//                     } else {
//                         $riqi_sql .= 'OR riqi_year between '.$years[0].' AND '.$years[1].' ';
//                     }
//                 }
//             }
//             if (!empty($param['zhuce'])) {
//                 foreach ($param['zhuce'] as &$v3) {
//                     if ($v3 == '20万以下') {
//                         if (empty($riqi_sql)) {
//                             $riqi_sql .= 'zhuce_amount < 200000 ';
//                         } else {
//                             $riqi_sql .= 'OR zhuce_amount < 200000 ';
//                         }
//                         continue;
//                     }
//                     if ($v3 == '500万以上') {
//                         if (empty($riqi_sql)) {
//                             $riqi_sql .= 'zhuce_amount >= 5000000 ';
//                         } else {
//                             $riqi_sql .= 'OR zhuce_amount >= 5000000 ';
//                         }
//                         continue;
//                     }
//                     $zhuce = explode('~',$v3);
//                     if (empty($riqi_sql)) {
//                         $riqi_sql .= 'zhuce_amount between '.($zhuce[0]*10000).' AND '.($zhuce[1]*10000).' ';
//                     } else {
//                         $riqi_sql .= 'OR zhuce_amount between '.($zhuce[0]*10000).' AND '.($zhuce[1]*10000).' ';
//                     }
//                 }
//             }
//             if (!empty($param['leixing'])) {
//                 $where[] = ['leixing','=',$param['leixing']];
//             }
//             if (!empty($param['canbao'])) {
//                 if ($param['canbao'] == '小于20人') {
//                     $where[] = ['canbao','<',$param['canbao']];
//                 } else {
//                     $where[] = ['canbao','between',[10,15]];
//                 }
//             }
//             if (!empty($param['zhaopin'])) {
//                 $where[] = ['zhaopin','=',$param['zhaopin']];
//             }
//             if (!empty($param['wangluo'])) {
//                 $where[] = ['wangluo','=',$param['wangluo']];
//             }
//             if (!empty($param['yuming'])) {
//                 $where[] = ['yuming','=',$param['yuming']];
//             }
//             if (!empty($param['shangbiao'])) {
//                 $where[] = ['shangbiao','=',$param['shangbiao']];
//             }
//             if (!empty($param['zhuanli'])) {
//                 $where[] = ['zhuanli','=',$param['zhuanli']];
//             }
//             if (!empty($param['zhaobiao'])) {
//                 $where[] = ['zhaobiao','=',$param['zhaobiao']];
//             }
//             if (!empty($param['gongzhong'])) {
//                 $where[] = ['gongzhong','=',$param['gongzhong']];
//             }
//             $list = $this->model->getNewsList($where,$param,$riqi_sql);
//             return table_assign(0, '', $list);
//         }
//         else{
//             $cate = Db::name('news_cate')->where(['delete_time'=>0,'pid'=>0])->order('sort asc')->select();
//             $cityList = Db::name('citys')->where(['level'=>1])->order('id asc')->select();
//             $svipCate = Db::name('news_file')->where(['delete_time'=>0])->order('sort asc')->select();
//             $uid = 0;
//             if (!empty($param['uid'])) {
//                 $uid = $param['uid'];
//             }
//             $qiCate = Db::name('qi_cate')->where(['delete_time'=>0])->order('id desc')->select();
//             View::assign('qiCate',$qiCate);
//             View::assign('uid',$uid);
//             View::assign('svipCate',$svipCate);
//             View::assign('cityList',$cityList);
//             View::assign('cate',$cate);
//             return view();
//         }
//     }
    /**
     * 数据列表
     */
    public function datalists()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $where   = [];
            $where[] = ["delete_time", "=", 0];
            $where[] = ["news_file_id", ">", 0];
            if (!empty($param['uid'])) {
                //查看公海信息
                $hai     = Db::name('hai')->where(['uid' => $param['uid'], 'type' => 1, 'delete_time' => 0])->column('news_id');
                $where[] = ['id', 'in', $hai];
            }
            if (!empty($param['news_file_id'])) {
                $where[] = ['news_file_id', '=', $param['news_file_id']];
            }
            if (!empty($param['province_id'])) {
                $province = Db::name('citys')->where('id', $param['province_id'])->value('name');
                $where[]  = ['province', 'like', "%{$province}%"];
            }
            if (!empty($param['city_id'])) {
                $city    = Db::name('citys')->where('id', $param['city_id'])->value('name');
                $where[] = ['city', 'like', "%{$city}%"];
            }
            if (!empty($param['district_id'])) {
                $district = Db::name('citys')->where('id', $param['district_id'])->value('name');
                $where[]  = ['district', 'like', "%{$district}%"];
            }
            if (!empty($param['cate_one'])) {
                $where[] = ['cate_one', '=', $param['cate_one']];
            }
            if (!empty($param['cate_two'])) {
                $where[] = ['cate_two', '=', $param['cate_two']];
            }
            if (!empty($param['yingye_id'])) {
                $yingye_id = implode('/', $param['yingye_id']);
                $ying      = explode('/', $yingye_id);
                $ying_arr  = array_merge($param['yingye_id'], $ying);
                $where[]   = ['status', 'in', $ying_arr];
            }
            if (!empty($param['lianxi'])) {
                foreach ($param['lianxi'] as &$v1) {
                    if ($v1 == '有电话') {
                        $where[] = ['mobile', '<>', ''];
                    } elseif ($v1 == '有固话') {
                        $where[] = ['mobile_more', '<>', ''];
                    } elseif ($v1 == '有邮箱') {
                        $where[] = ['emails', '<>', ''];
                    } elseif ($v1 == '有QQ') {
                        $where[] = ['qq', '<>', ''];
                    } elseif ($v1 == '无联系方式') {
                        $where[] = ['mobile', '=', ''];
                        $where[] = ['mobile_more', '=', ''];
                    }
                }
            }
            $riqi_sql = '';
            if (!empty($param['riqi_year'])) {
                foreach ($param['riqi_year'] as &$v2) {
                    if ($v2 == '1年以内') {
                        if (empty($riqi_sql)) {
                            $riqi_sql .= 'riqi_year < 1 ';
                        } else {
                            $riqi_sql .= 'OR riqi_year < 1 ';
                        }
                        continue;
                    }
                    if ($v2 == '15年以上') {
                        if (empty($riqi_sql)) {
                            $riqi_sql .= 'riqi_year >= 15 ';
                        } else {
                            $riqi_sql .= 'OR riqi_year >= 15 ';
                        }
                        continue;
                    }
                    $years = explode('-', $v2);
                    if (empty($riqi_sql)) {
                        $riqi_sql .= 'riqi_year between ' . $years[0] . ' AND ' . $years[1] . ' ';
                    } else {
                        $riqi_sql .= 'OR riqi_year between ' . $years[0] . ' AND ' . $years[1] . ' ';
                    }
                }
            }
            if (!empty($param['zhuce'])) {
                foreach ($param['zhuce'] as &$v3) {
                    if ($v3 == '20万以下') {
                        if (empty($riqi_sql)) {
                            $riqi_sql .= 'zhuce < 20 ';
                        } else {
                            $riqi_sql .= 'OR zhuce < 20 ';
                        }
                        continue;
                    }
                    if ($v3 == '500万以上') {
                        if (empty($riqi_sql)) {
                            $riqi_sql .= 'zhuce >= 500 ';
                        } else {
                            $riqi_sql .= 'OR zhuce >= 500 ';
                        }
                        continue;
                    }
                    $zhuce = explode('~', $v3);
                    if (empty($riqi_sql)) {
                        $riqi_sql .= 'zhuce between ' . $zhuce[0] . ' AND ' . $zhuce[1] . ' ';
                    } else {
                        $riqi_sql .= 'OR zhuce between ' . $zhuce[0] . ' AND ' . $zhuce[1] . ' ';
                    }
                }
            }
            if (!empty($param['leixing'])) {
                $where[] = ['leixing', '=', $param['leixing']];
            }
            if (!empty($param['canbao'])) {
                if ($param['canbao'] == '小于20人') {
                    $where[] = ['canbao', '<', $param['canbao']];
                } else {
                    $where[] = ['canbao', 'between', [10, 15]];
                }
            }
            if (!empty($param['zhaopin'])) {
                $where[] = ['zhaopin', '=', $param['zhaopin']];
            }
            if (!empty($param['wangluo'])) {
                $where[] = ['wangluo', '=', $param['wangluo']];
            }
            if (!empty($param['yuming'])) {
                $where[] = ['yuming', '=', $param['yuming']];
            }
            if (!empty($param['shangbiao'])) {
                $where[] = ['shangbiao', '=', $param['shangbiao']];
            }
            if (!empty($param['zhuanli'])) {
                $where[] = ['zhuanli', '=', $param['zhuanli']];
            }
            if (!empty($param['zhaobiao'])) {
                $where[] = ['zhaobiao', '=', $param['zhaobiao']];
            }
            if (!empty($param['gongzhong'])) {
                $where[] = ['gongzhong', '=', $param['gongzhong']];
            }
            $list = $this->model->getNewsList($where, $param, $riqi_sql);
            return table_assign(0, '', $list);
        } else {
            $cate     = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0])->order('sort asc')->select();
            $cityList = Db::name('citys')->where(['level' => 1])->order('id asc')->select();
            $svipCate = Db::name('news_file')->where(['delete_time' => 0])->order('sort asc')->select();
            $uid      = 0;
            if (!empty($param['uid'])) {
                $uid = $param['uid'];
            }
            $qiCate = Db::name('qi_cate')->where(['delete_time' => 0])->order('id desc')->select();
            View::assign('qiCate', $qiCate);
            View::assign('uid', $uid);
            View::assign('svipCate', $svipCate);
            View::assign('cityList', $cityList);
            View::assign('cate', $cate);
            return view();
        }
    }


    /**
     * 导入
     */
    public function btnImport()
    {
        $logFile = '/www/wwwroot/adminapi.qypwhbfw.com/public/error.log';
        try {
            $shared = new \PHPExcel_Shared_Date();
            $param  = request()->param();
            if (empty($param['filepath'])) {
                return error('请先上传文件');
            }
            $param['filepath'] = app()->getRootPath() . '/public' . $param['filepath'];
            if (!file_exists($param['filepath'])) {
                return error("文件不存在", false);
            }
            $filePath    = $param['filepath'];
            $spreadsheet = IOFactory::load($filePath);
            $sheet       = $spreadsheet->getActiveSheet();
            // 处理文件数据
            $data = [];
            foreach ($sheet->getRowIterator() as $row) {
                $rowIndex = $row->getRowIndex();
                // 不读取第一行 标题
                if ($rowIndex == 1) {
                    continue;
                }
                $cellIterator = $row->getCellIterator();
                $row          = [];
                foreach ($cellIterator as $cell) {
                    $row[] = $cell->getValue();
                }
                $data[] = $row;
            }
            if (empty($data)) {
                return error('暂无数据');
            }

            $insert = [];
            $i      = 0;

            foreach ($data as $k => $v) {
                if (empty($v[0])) {
                    continue;
                }
                $insert[$i]['name']   = $v[0];
                $insert[$i]['status'] = $v[1];
                $insert[$i]['faren']  = $v[2];
                $insert[$i]['riqi']   = $v[3];
                //计算成立年限
                if (!empty($v[3])) {
                    $insert[$i]['riqi_year'] = intval(date('Y') - date('Y', strtotime($v[3])));
                }
                $insert[$i]['province']    = $v[4];
                $insert[$i]['city']        = $v[5];
                $insert[$i]['district']    = $v[6];
                $insert[$i]['daima']       = $v[7];
                $insert[$i]['mobile']      = $v[8];
                $insert[$i]['mobile_more'] = $v[9];
                $insert[$i]['address']     = $v[10];
                $insert[$i]['leixing']     = $v[11];
                $insert[$i]['canbao']      = $v[12];
                $insert[$i]['zhaopin']     = $v[13];
                $insert[$i]['wangluo']     = $v[14];
                $insert[$i]['yuming']      = $v[15];
                $insert[$i]['shangbiao']   = $v[16];
                $insert[$i]['zhuanli']     = $v[17];
                $insert[$i]['zhaobiao']    = $v[18];
                $insert[$i]['gongzhong']   = $v[19];
                $insert[$i]['emails']      = $v[20];
                $insert[$i]['qq']          = $v[21];
                $insert[$i]['zhuce']       = $v[22];
                $insert[$i]['jingying']    = $v[23];
                $cate_one                  = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0, 'title' => $v[24]])->value('id');
                $cate_two                  = Db::name('news_cate')
                                               ->where([['delete_time', '=', 0], ['pid', '>', 0], ['title', '=', $v[25]]])
                                               ->find();
                //查找二级分类ID
                $insert[$i]['cate_two'] = !empty($cate_two) ? $cate_two['id'] : 0;
                if (empty($cate_one) && !empty($cate_two)) {
                    $insert[$i]['cate_one'] = $cate_two['pid'];
                } else {
                    //查找一级分类ID
                    $insert[$i]['cate_one'] = $cate_one;
                }
                //获取经纬度
                $location          = getLocation($v[4] . $v[5] . $v[6]);
                $insert[$i]['lng'] = $location['lng'];
                $insert[$i]['lat'] = $location['lat'];

                $insert[$i]['create_time'] = time();
                if (!empty($param['svip_cate_id'])) {
                    $insert[$i]['news_file_id'] = $param['svip_cate_id'];
                }
                if ($param['dr_type'] == 3) {
                    //导入并更新
                    if (!empty($param['svip_cate_id'])) {
                        $is_have = Db::name('news')->where([['daima', '=', $v[7]], ['news_file_id', '=', $param['svip_cate_id']], ['delete_time', '=', 0]])->find();
                    } else {
                        $is_have = Db::name('news')->where(['daima' => $v[7], 'news_file_id' => 0, 'delete_time' => 0])->find();
                    }

                    $up       = [
                        'name'        => $v[0],
                        'status'      => $v[1],
                        'faren'       => $v[2],
                        'riqi'        => $v[3],
                        'riqi_year'   => empty($v[3]) ? '' : intval(date('Y') - date('Y', strtotime($v[3]))),
                        'province'    => $v[4],
                        'city'        => $v[5],
                        'district'    => $v[6],
                        'daima'       => $v[7],
                        'mobile'      => $v[8],
                        'mobile_more' => $v[9],
                        'address'     => $v[10],
                        'leixing'     => $v[11],
                        'canbao'      => $v[12],
                        'zhaopin'     => $v[13],
                        'wangluo'     => $v[14],
                        'yuming'      => $v[15],
                        'shangbiao'   => $v[16],
                        'zhuanli'     => $v[17],
                        'zhaobiao'    => $v[18],
                        'gongzhong'   => $v[19],
                        'emails'      => $v[20],
                        'qq'          => $v[21],
                        'zhuce'       => $v[22],
                        'jingying'    => $v[23],
                        //                    'cate_one' => Db::name('news_cate')->where(['delete_time'=>0,'pid'=>0,'title'=>$v[24]])->value('id'),
                        //                    'cate_two' => Db::name('news_cate')
                        //                        ->where([['delete_time','=',0],['pid','>',0],['title','=',$v[25]]])
                        //                        ->value('id'),
                        'lng'         => $location['lng'],
                        'lat'         => $location['lat'],
                        'has_mobile'  => -1,
                        'create_time' => time(),
                    ];
                    $cate_one = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0, 'title' => $v[24]])->value('id');
                    $cate_two = Db::name('news_cate')
                                  ->where([['delete_time', '=', 0], ['pid', '>', 0], ['title', '=', $v[25]]])
                                  ->find();
                    //查找二级分类ID
                    $up['cate_two'] = !empty($cate_two) ? $cate_two['id'] : 0;
                    if (empty($cate_one) && !empty($cate_two)) {
                        $up['cate_one'] = $cate_two['pid'];
                    } else {
                        //查找一级分类ID
                        $up['cate_one'] = $cate_one;
                    }
                    if (!empty($param['svip_cate_id'])) {
                        $up['news_file_id'] = $param['svip_cate_id'];
                    }
                    if (!empty($is_have)) {
                        // 检查每个字段，如果新数据为空但原数据有值，则保留原数据
                        foreach ($up as $key => $value) {
                            if ((empty($value) || $value === '') && isset($is_have[$key]) && !empty($is_have[$key])) {
                                $up[$key] = $is_have[$key];
                            }
                        }
                        Db::name('news')->where(['id' => $is_have['id']])->update($up);
                    } else {
                        //再根据名称去判断
                        if (!empty($param['svip_cate_id'])) {
                            $is_have = Db::name('news')->where(['name' => $v[0], 'news_file_id' => $param['svip_cate_id'], 'delete_time' => 0])->find();
                        } else {
                            $is_have = Db::name('news')->where(['name' => $v[0], 'news_file_id' => 0, 'delete_time' => 0])->find();
                        }
                        if (!empty($is_have)) {
                            // 检查每个字段，如果新数据为空但原数据有值，则保留原数据
                            foreach ($up as $key => $value) {
                                if ((empty($value) || $value === '') && isset($is_have[$key]) && !empty($is_have[$key])) {
                                    $up[$key] = $is_have[$key];
                                }
                            }
                            Db::name('news')->where(['id' => $is_have['id']])->update($up);
                        } else {
                            Db::name('news')->insert($up);
                        }
                    }
                }
                $i++;
            }
            if ($param['dr_type'] == 1) {
                //纯导入
                Db::name('news')->insertAll($insert);
            } elseif ($param['dr_type'] == 2) {
                //导入并覆盖
                $names = array_column($insert, 'name');
                Db::name('news')->where([['name', 'in', $names]])->delete();
                Db::name('news')->insertAll($insert);
            }

            return success('导入成功');
        } catch (\Exception $e) {
            // 记录错误信息到日志文件中
            error_log($e->getMessage(), 3, $logFile);
            return error('导入失败,请检查文件数据后重试');
        }

    }

    /**
     * 上传文件
     */
    public function uploadFile()
    {
        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', '', $error);
        if (!$result) {
            return error($error);
        }
        return success('上传成功', $result);
    }

    /**
     * 添加
     */
    public function add()
    {
        if (request()->isAjax()) {
            $param = get_params();
            if (!empty($param['province_id'])) {
                $param['province'] = Db::name('citys')->where('id', $param['province_id'])->value('name');
            } else {
                $param['province'] = '';
            }
            if (!empty($param['city_id'])) {
                $param['city'] = Db::name('citys')->where('id', $param['city_id'])->value('name');
            } else {
                $param['city'] = '';
            }
            if (!empty($param['district_id'])) {
                $param['district'] = Db::name('citys')->where('id', $param['district_id'])->value('name');
            } else {
                $param['district'] = '';
            }
            $location     = getLocation($param['province'] . $param['city'] . $param['district'] . $param['address']);
            $param['lng'] = $location['lng'];
            $param['lat'] = $location['lat'];
            //成立年限
            if (!empty($param['riqi'])) {
                $year               = date('Y');
                $riqi               = date('Y', strtotime($param['riqi']));
                $param['riqi_year'] = intval($year - $riqi);
            }
            // 检验完整性
            try {
                validate(NewsValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $this->model->addNews($param);
        } else {
            $cate     = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0])->order('sort asc')->select();
            $cityList = Db::name('citys')->where(['level' => 1])->order('id asc')->select();
            $svipCate = Db::name('news_file')->where(['delete_time' => 0])->order('sort desc')->select();
            $qiCate   = Db::name('qi_cate')->where(['delete_time' => 0])->order('id desc')->select();
            View::assign('qiCate', $qiCate);
            View::assign('svipCate', $svipCate);
            View::assign('cityList', $cityList);
            View::assign('cate', $cate);
            return view();
        }
    }

    public function getcity()
    {
        $get  = get_params();
        $data = Db::name('citys')->where(['level' => 2, 'pid' => $get['id']])->order('id asc')->select();
        return success('成功', ['data' => $data]);
    }

    public function getdis()
    {
        $get  = get_params();
        $data = Db::name('citys')->where(['level' => 3, 'pid' => $get['id']])->order('id asc')->select();
        return success('操作成功', ['data' => $data]);
    }


    /**
     * 编辑
     */
    public function edit()
    {
        $param               = get_params();
        $param['has_mobile'] = -1;
        if (request()->isAjax()) {
            if (!empty($param['province_id'])) {
                $param['province'] = Db::name('citys')->where('id', $param['province_id'])->value('name');
            } else {
                $param['province'] = '';
            }
            if (!empty($param['city_id'])) {
                $param['city'] = Db::name('citys')->where('id', $param['city_id'])->value('name');
            } else {
                $param['city'] = '';
            }
            if (!empty($param['district_id'])) {
                $param['district'] = Db::name('citys')->where('id', $param['district_id'])->value('name');
            } else {
                $param['district'] = '';
            }
            $location     = getLocation($param['province'] . $param['city'] . $param['district'] . $param['address']);
            $param['lng'] = $location['lng'];
            $param['lat'] = $location['lat'];
            //成立年限
            if (!empty($param['riqi'])) {
                $year               = date('Y');
                $riqi               = date('Y', strtotime($param['riqi']));
                $param['riqi_year'] = intval($year - $riqi);
            }
            // 检验完整性
            try {
                validate(NewsValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $this->model->editNews($param);
        } else {
            $id     = isset($param['id']) ? $param['id'] : 0;
            $detail = $this->model->getNewsById($id);
            if (!empty($detail)) {
                $save = [];
                if (!empty($detail['province']) && empty($detail['province_id'])) {
                    $province_id = Db::name('citys')->where(['name' => $detail['province'], 'level' => 1])->value('id');
                    if (!empty($province_id)) {
                        $save['province_id'] = $province_id;
                    }
                }
                if (!empty($detail['city']) && empty($detail['city_id'])) {
                    $city_id = Db::name('citys')->where(['name' => $detail['city'], 'level' => 2])->value('id');
                    if (!empty($city_id)) {
                        $save['city_id'] = $city_id;
                    }
                }
                if (!empty($detail['district']) && empty($detail['district_id'])) {
                    $district_id = Db::name('citys')->where(['name' => $detail['district'], 'level' => 3])->value('id');
                    if (!empty($district_id)) {
                        $save['district_id'] = $district_id;
                    }
                }
                if (!empty($save)) {
                    Db::name('news')->where('id', $id)->update($save);
                }
                $detail   = $this->model->getNewsById($id);
                $cate     = Db::name('news_cate')->where(['delete_time' => 0, 'pid' => 0])->order('sort asc')->select();
                $cityList = Db::name('citys')->where(['level' => 1])->order('id asc')->select();
                //二级分类
                $two_cate = Db::name('news_cate')
                              ->where(['pid' => $detail['cate_one'], 'delete_time' => 0])->order('id desc')->select();
                $city     = [];
                $dis      = [];
                if (!empty($detail['province_id'])) {
                    $city = Db::name('citys')->where(['level' => 2, 'pid' => $detail['province_id']])->order('id asc')->select();
                }
                if (!empty($detail['city_id'])) {
                    $dis = Db::name('citys')->where(['level' => 3, 'pid' => $detail['city_id']])->order('id asc')->select();
                }
                $svipCate = Db::name('news_file')->where(['delete_time' => 0])->order('sort desc')->select();
                $qiCate   = Db::name('qi_cate')->where(['delete_time' => 0])->order('id desc')->select();
                View::assign('qiCate', $qiCate);
                View::assign('svipCate', $svipCate);
                View::assign('city', $city);
                View::assign('dis', $dis);
                View::assign('two_cate', $two_cate);
                View::assign('cityList', $cityList);
                View::assign('cate', $cate);
                View::assign('detail', $detail);
                return view();
            } else {
                throw new \think\exception\HttpException(404, '找不到页面');
            }
        }
    }

    /**
     * 获取二级分类
     */
    public function getCate()
    {
        $param = get_params();
        if (empty($param['id'])) {
            return success('');
        }
        $data = Db::name('news_cate')
                  ->where(['pid' => $param['id'], 'delete_time' => 0])->order('sort asc')->select();
        return success('获取成功', $data);
    }


    /**
     * 查看信息
     */
    public function read()
    {
        $param  = get_params();
        $id     = isset($param['id']) ? $param['id'] : 0;
        $detail = $this->model->getNewsById($id);
        if (!empty($detail)) {
            $detail['cate_name'] = '';
            if (!empty($detail['cate_one'])) {
                $cate_one            = Db::name('news_cate')->where('id', $detail['cate_one'])->value('title');
                $detail['cate_name'] = $cate_one;
            }
            if (!empty($detail['cate_two'])) {
                $cate_two            = Db::name('news_cate')->where('id', $detail['cate_two'])->value('title');
                $detail['cate_name'] = $detail['cate_name'] . '-' . $cate_two;
            }
            $detail['news_file_name'] = '';
            if (!empty($detail['news_file_id'])) {
                $detail['news_file_name'] = Db::name('news_file')->where('id', $detail['news_file_id'])->value('title');
            }
            View::assign('detail', $detail);
            return view();
        } else {
            throw new \think\exception\HttpException(404, '找不到页面');
        }
    }

    /**
     * 删除
     * type=0,逻辑删除，默认
     * type=1,物理删除
     */
    public function del()
    {
        $param = get_params();
        $id    = isset($param['id']) ? $param['id'] : 0;
        $type  = isset($param['type']) ? $param['type'] : 1;

        $this->model->delNewsById($id, $type);
    }

    /**
     * 批量删除
     */
    public function dels()
    {
        $param = get_params();
        if (empty($param['ids'])) {
            return to_assign(1, '请选择要删除的数据');
        }
        Db::name('news')->where([['id', 'in', $param['ids']]])->update(['delete_time' => time()]);
        Db::name('news')->where([['id', 'in', $param['ids']]])->delete();
        return to_assign(0, '删除成功');
    }
}
